

import UIKit
 
extension UIViewController {
   
    func removeNavChildViewControllers(_ controllers: [String]) -> [UIViewController] {
        guard let navigationController = self.navigationController,
              !navigationController.viewControllers.isEmpty else {
            return []
        }
        
        guard !controllers.isEmpty else {
            return navigationController.viewControllers
        }
        
        var array = navigationController.viewControllers
        
        // 遍历需要移除的控制器类名
        controllers.forEach { targetController in
            // 遍历当前视图控制器栈，移除匹配的控制器
            array.removeAll { controller in
                String(describing: type(of: controller)) == targetController
            }
        }
        return array
    }

    func dismissToRootViewController(animated: Bool, completion: (() -> Void)? = nil) {
        var vc: UIViewController? = self
        while vc?.presentingViewController != nil {
            vc = vc?.presentingViewController
        }
        vc?.dismiss(animated: animated, completion: completion)
    }
    
    func alert(title: String?, message: String?, preferredStyle: UIAlertController.Style = .alert, leftButtonName: String? = nil, leftStyle: UIAlertAction.Style = .default, leftButtonAction:(() -> Void)? = nil, rightButtonName: String? = nil, rightStyle: UIAlertAction.Style = .default, rightButtonAction:(() -> Void)? = nil) {
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
        
        if leftButtonName != nil {
            alert.addAction(UIAlertAction(title: leftButtonName, style: leftStyle, handler: { alertAction in
                leftButtonAction?()
            }))
        }
        
        if rightButtonName != nil {
            alert.addAction(UIAlertAction(title: rightButtonName, style: rightStyle, handler: { alertAction in
                rightButtonAction?()
            }))
        }
        present(alert, animated: true)
    }
}




